package io.sundial.job.bind.impl;

import io.sundial.job.JobContext;
import io.sundial.job.JobParameter;
import io.sundial.job.bind.JobData;
import io.sundial.job.bind.JobField;
import io.sundial.job.bind.JobResolver;
import io.sundial.util.StrKit;

import java.text.DateFormat;

/**
 * 日期 转换器
 *
 * @author Payne 646742615@qq.com
 * 2019/1/7 17:58
 */
public class DateResolver implements JobResolver {

    @Override
    public boolean supports(JobField field) {
        return field.type == java.util.Date.class
                || field.type == java.sql.Date.class
                || field.type == java.sql.Time.class
                || field.type == java.sql.Timestamp.class;
    }

    @Override
    public JobParameter resolve(JobField field) {
        String value = field.value == null ? null
                : field.type == java.util.Date.class ? DateFormat.getInstance().format(field.value)
                : field.type == java.sql.Date.class ? field.value.toString()
                : field.type == java.sql.Time.class ? field.value.toString()
                : field.type == java.sql.Timestamp.class ? field.value.toString()
                : null;
        return new JobParameter(field.name)
                .setEditor("text")
                .setValue(value);
    }

    @Override
    public Object resolve(JobField field, JobData data, JobContext context) throws Exception {
        String value = data.get(field.name);
        return StrKit.isEmpty(value) ? DEFAULT
                : field.type == java.util.Date.class ? DateFormat.getInstance().parse(value)
                : field.type == java.sql.Date.class ? java.sql.Date.valueOf(value)
                : field.type == java.sql.Time.class ? java.sql.Time.valueOf(value)
                : field.type == java.sql.Timestamp.class ? java.sql.Timestamp.valueOf(value)
                : DEFAULT;
    }
}
